package mt.ctrl;

import io.rong.ApiHttpClient;
import io.rong.models.FormatType;
import io.rong.models.SdkHttpResult;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import mt.Const;
import mt.business.Cache;
import mt.business.UserVO;
import mt.model.User;

import org.apache.commons.lang.StringUtils;

import base.ctrl.BaseController;
import base.ctrl.BaseResult;
import base.jfinal.JsonUtil;
import base.jfinal.anatation.RouteBind;
import base.util.HttpRequestUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

@RouteBind(path = "user")
public class UserCtrl extends BaseController {
	public static String AppId = "wxdbe291f97a88a43d";
	public static String Secret = "eb6cfd85a8d0bf3e6b22a1ca0762d429";

	// 用于APP调用
	public void loginFromWX() {
		String wxcode = getPara("code", "");
		if (wxcode == "") {
			this.renderJson("{\"errmsg\":\"无效参数\"}");
			return;
		}
		JSONObject accessToken = HttpRequestUtils.httpGet("https://api.weixin.qq.com/sns/oauth2/access_token?appid="
				+ AppId + "&secret=" + Secret + "&code=" + wxcode + "&grant_type=authorization_code");
		if (accessToken == null || accessToken.getString("access_token") == "") {
			this.renderJson("{\"errmsg\":\"微信登录失败，请重试！\"}");
			return;
		}
		JSONObject userInfo = HttpRequestUtils.httpGet("https://api.weixin.qq.com/sns/userinfo?access_token="
				+ accessToken.getString("access_token") + "&openid=" + accessToken.getString("openid"));
		if (userInfo == null || userInfo.getString("openid") == "") {
			this.renderJson("{\"errmsg\":\"微信登录失败，请重试！\"}");
			return;
		}
		String openId = userInfo.getString("openid");
		Record userCount = Db.findFirst("select userId,userName from mt_user where openid = ?", openId);
		if (userCount == null) {// 用户不存在，用户注册
			User user = new User();
			user.set("openid", userInfo.getString("openid"));
			user.set("userName", userInfo.getString("nickname"));
			user.set("nickName", userInfo.getString("nickname"));
			user.set("sex", userInfo.getIntValue("sex"));
			user.set("province", userInfo.getString("province"));
			user.set("city", userInfo.getString("city"));
			user.set("country", userInfo.getString("country"));
			user.set("headimgurl", userInfo.getString("headimgurl"));
			user.set("unionid", userInfo.getString("unionid"));
			user.set("wxcode", wxcode);
			user.set("createDate", (new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date()));
			String imtoken = getImToken(userInfo);
			user.set("imtoken", imtoken);
			user.save();

			userCount = Db.findFirst("select userId,userName from mt_user where openid = ?", openId);
			UserVO userVO = new UserVO();
			userVO.setUserId(userCount.getInt("userId"));
			userVO.setUserName(userCount.getStr("userName"));
			userVO.setCode(wxcode);
			Cache.PutUserVO(userVO);
			JsonUtil result = new JsonUtil();
			result.put("code", wxcode);
			result.put("userid", userInfo.getString("openid"));
			result.put("username", userInfo.getString("nickname"));
			result.put("headimgurl", userInfo.getString("headimgurl"));
			result.put("sex", userInfo.getIntValue("sex") + "");
			result.put("imtoken", imtoken);
			this.renderJson(result.toString());
		} else {// 用户存在，重新登录
			Db.update("update mt_user set wxcode=?,userName=? where openid = ?", wxcode, userInfo.getString("nickname"),
					openId);
			User user = new User();
			user = user.findById(userCount.getInt("userId"));
			user.set("userName", userInfo.getString("nickname"));
			user.set("nickName", userInfo.getString("nickname"));
			user.set("sex", userInfo.getIntValue("sex"));
			user.set("province", userInfo.getString("province"));
			user.set("city", userInfo.getString("city"));
			user.set("country", userInfo.getString("country"));
			user.set("headimgurl", userInfo.getString("headimgurl"));
			user.set("unionid", userInfo.getString("unionid"));
			user.set("wxcode", wxcode);

			UserVO userVO = new UserVO();
			userVO.setUserId(userCount.getInt("userId"));
			userVO.setUserName(userInfo.getString("nickname"));
			userVO.setCode(wxcode);
			Cache.PutUserVO(userVO);

			String imtoken = user.getStr("imtoken");
			if (imtoken == null || imtoken == "") {
				imtoken = getImToken(userInfo);
			}
			user.set("imtoken", imtoken);
			user.update();

			JsonUtil result = new JsonUtil();
			result.put("code", wxcode);
			result.put("userid", userInfo.getString("openid"));
			result.put("username", userInfo.getString("nickname"));
			result.put("headimgurl", userInfo.getString("headimgurl"));
			result.put("sex", userInfo.getIntValue("sex") + "");
			result.put("imtoken", imtoken);
			System.out.println(result.toString());
			this.renderJson(result.toString());
		}
	}

	private String getImToken(JSONObject userInfo) {
		try {
			SdkHttpResult result = ApiHttpClient.getToken(Const.IM_KEY, Const.IM_SECRET, userInfo.getString("openid"),
					userInfo.getString("nickname"), userInfo.getString("headimgurl"), FormatType.json);
			JSONObject resultJson = JSON.parseObject(result.getResult());
			if (resultJson.getIntValue("code") == 200) {
				return resultJson.getString("token");
			} else {
				System.out.println("gettoken=" + result.getResult());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	// 用于APP调用 用户信息可以缓存，只有重新登录时需要重新修改
	public void getInfo() {
		Record userInfo = Db.findFirst("select username,sex,headimgurl from mt_user where wxcode = ?", getPara("code"));
		if (userInfo == null) {
			this.renderJson("{\"errmsg\":\"无效参数\"}");
		} else {
			this.renderJson(userInfo.toJson());
		}
	}

	// 获取个人评价
	public void getEvaluate() {
		String code = getPara("code", "");
		int userId = Cache.GetUserVOByCode(code).getUserId();
		String selectEvaSql = "SELECT mu.reply,mu.userid,mu.evalStar,mt.themeid,mu.content,mu.createDate,mu.photo,muf.username,mt.themename,muf.headimgurl,mu.createDate,mu.themeid FROM mt_theme_eval mu,mt_user muf,mt_theme mt WHERE mu.userid=muf.userid and mu.themeid=mt.themeid and muf.userid=?";
		List<Record> list = Db.find(selectEvaSql, userId);
		this.renderJson((new JsonUtil(list)).toString());
	}

	// 获取个人玩过的密室
	public void getExperience() {
		String code = getPara("code", "");
		int userId = Cache.GetUserVOByCode(code).getUserId();
		String selectSql = "SELECT ma.themeid,mb.themename,mb.photo,mb.content,mb.price,mb.soldnum,mb.evalstar,mb.coverimg,mc.street,mc.area,mc.shopname,mc.shopid from mt_team ma,mt_theme mb,mt_shop mc,mt_user md,mt_team_user me where me.userid=md.userid and ma.teamid=me.teamid and ma.themeid=mb.themeid and mb.shopid=mc.shopid and md.userid=?;";
		List<Record> list = Db.find(selectSql, userId);
		if (list != null) {
			for (Record record : list) {
				BigDecimal price = record.getBigDecimal("price");
				record.getColumns().put("displayprice", price != null ? price.divide(new BigDecimal(100)) : 0);
			}
		}
		this.renderJson((new JsonUtil(list)).toString());
	}

	// 用于APP调用 每次进入我的页面时都需要刷新一次
	public void getStatus() {
		Record userInfo = Db.findFirst(
				"select experience,couponCount,evalCount,favoriteCount from mt_user where wxcode = ?", getPara("code"));
		if (userInfo == null) {
			this.renderJson("{\"errmsg\":\"无效参数\"}");
		} else {
			this.renderJson(userInfo.toJson());
		}
	}

	// 主题经历
	public void experience() {
		String code = getPara("code", "");
		int experience = getParaToInt("experience");
		if (code == "" || experience == 0) {
			this.renderJson("{\"errmsg\":\"无效参数\"}");
		}
		int userId = Cache.GetUserVOByCode(code).getUserId();
		Db.update("", userId, experience);
		this.renderJson("{\"errmsg\":\"\"}");
	}

	// 收藏店铺
	public void collectShop() {
		String code = getPara("code", "");
		int shopid = getParaToInt("shopid");
		if (code == "" || shopid == 0) {
			this.renderJson("{\"errmsg\":\"无效参数\"}");
		}
		int userId = Cache.GetUserVOByCode(code).getUserId();
		System.out.println("collectTheme : "
				+ Db.update("insert into mt_user_favorites_shop(userId,shopid) values(?,?)", userId, shopid));
		this.renderJson("{\"errmsg\":\"\"}");
	}

	// 收藏主题
	public void collectTheme() {
		String code = getPara("code", "");
		int themeId = getParaToInt("themeid");
		if (code == "" || themeId == 0) {
			this.renderJson("{\"errmsg\":\"无效参数\"}");
		}
		int userId = Cache.GetUserVOByCode(code).getUserId();
		Db.update("insert into mt_user_favorites_theme(userId,themeId) values(?,?)", userId, themeId);
		this.renderJson("{\"errmsg\":\"\"}");
	}

	// 删除好友
	public void unFriend() {
		String code = getPara("code", "");
		String friendIds = getPara("friendid", "");
		if (StringUtils.isBlank(code) || StringUtils.isBlank(friendIds)) {
			this.renderJson("{\"errmsg\":\"无效参数\"}");
		}

		int userId = Cache.GetUserVOByCode(code).getUserId();
		List<Object> params = new ArrayList<Object>();
		StringBuilder delSqlBd = new StringBuilder("delete from mt_user_friends  WHERE userId= ? and friendId in (");
		params.add(userId);

		String[] friendIdArr = StringUtils.split(friendIds, ";");
		for (int i = 0; i < friendIdArr.length; i++) {
			if (!StringUtils.isNumeric(friendIdArr[i])) {
				continue;
			}
			params.add(friendIdArr[i]);
			delSqlBd.append("?");
			if (i == friendIdArr.length - 1) {
				delSqlBd.append(")");
			} else {
				delSqlBd.append(",");
			}
		}
		Db.update(delSqlBd.toString(), params.toArray());
		this.renderJson("{\"errmsg\":\"\"}");
	}

	// 发表评价
	public void Evaluate() {
		BaseResult<Object> reuslt = new BaseResult<Object>(false);
		String code = getPara("code", "");
		int themeid = getParaToInt("themeid");
		int evalStar = getParaToInt("evalStar");
		String content = getPara("content");
		String photo = getPara("photo");
		if (code == "" || themeid == 0) {
			renderJson(reuslt.setMessage("操作失败，参数无效！").toJsonString());
		}

		int userid = Cache.GetUserVOByCode(code).getUserId();
		int count = Db.update(
				"insert into mt_theme_eval(evalStar,content,userid,createDate,themeid,photo) VALUES(?,?,?,?,?,?);",
				evalStar, content, userid, new Date(), themeid, photo);
		renderJson(reuslt.setSuccess(count > 0).setMessage(count > 0 ? "操作成功" : "操作失败，未知异常！").toJsonString());
	}

	// 添加好友
	public void addFriend() {
		String code = getPara("code", "");
		int friendId = getParaToInt("userid");
		if (code == "" || friendId == 0) {
			this.renderJson("{\"errmsg\":\"无效参数\"}");
		}
		int userId = Cache.GetUserVOByCode(code).getUserId();
		System.out.println("addFriends : "
				+ Db.update("insert into mt_user_friends(userId,friendId) values(?,?)", userId, friendId));
		this.renderJson("{\"errmsg\":\"\"}");
	}

	// APP中调用 查询好友列表
	public void getFriends() {
		String code = getPara("code", "");
		int userId = Cache.GetUserVOByCode(code).getUserId();
		String selectSql = "SELECT mu.userid,mu.username,mu.headimgurl FROM mt_user_friends muf,mt_user mu where mu.userid = muf.friendid and muf.userid=?;";
		List<Record> list = Db.find(selectSql, userId);
		this.renderJson((new JsonUtil(list)).toString());
	}

}